<?php
/**
 * Starkers functions and definitions
 *
 * For more information on hooks, actions, and filters, see http://codex.wordpress.org/Plugin_API.
 *
 * @package 	WordPress
 * @subpackage 	Starkers
 * @since 		Starkers 4.0
 */
/* ========================================================================================================================

  Required external files

  ======================================================================================================================== */

require_once( 'external/starkers-utilities.php' );

/* ========================================================================================================================

  Theme specific settings

  Uncomment register_nav_menus to enable a single menu with the title of "Primary Navigation" in your theme

  ======================================================================================================================== */

add_theme_support('post-thumbnails');

// register_nav_menus(array('primary' => 'Primary Navigation'));

/* ========================================================================================================================

  Actions and Filters

  ======================================================================================================================== */

add_action('wp_enqueue_scripts', 'script_enqueuer');

add_filter('body_class', 'add_slug_to_body_class');

/* ========================================================================================================================

  Custom Post Types - include custom post types and taxonimies here e.g.

  e.g. require_once( 'custom-post-types/your-custom-post-type.php' );

  ======================================================================================================================== */



/* ========================================================================================================================

  Scripts

  ======================================================================================================================== */

/**
 * Add scripts via wp_head()
 *
 * @return void
 * @author Keir Whitaker
 */
function script_enqueuer() {
    wp_enqueue_script('site', get_template_directory_uri() . '/js/site.js', array('jquery','jquery-ui-core','jquery-effects-core'));
	wp_enqueue_script('bootstrap_js', get_template_directory_uri() . '/js/bootstrap.js');
	wp_enqueue_script('cslider', get_template_directory_uri() . '/js/jquery.cslider.js');
	wp_enqueue_script('cookie', get_template_directory_uri() . '/js/jquery.cookie.js');
	wp_enqueue_script('pretty', get_template_directory_uri() . '/js/jquery.prettyPhoto.js');
	wp_enqueue_script('modernizer', get_template_directory_uri() . '/js/modernizr.custom.28468.js');
	wp_enqueue_script('options', get_template_directory_uri() . '/js/options.js');


	wp_enqueue_style('screen_css', get_template_directory_uri() . '/style.css', '', '', 'screen');
	wp_enqueue_style('bootstrap_css', get_template_directory_uri() . '/css/bootstrap.css');
	wp_enqueue_style('bootstrap_responsive_css', get_template_directory_uri() . '/css/bootstrap-responsive.css');
	wp_enqueue_style('paralax_css', get_template_directory_uri() . '/css/parallax.css');
	wp_enqueue_style('pretty_css', get_template_directory_uri() . '/css/prettyPhoto.css');
	wp_enqueue_style('style_css', get_template_directory_uri() . '/css/style.css');
}

/* ========================================================================================================================

  Comments

  ======================================================================================================================== */

/**
 * Custom callback for outputting comments
 *
 * @return void
 * @author Keir Whitaker
 */
function starkers_comment($comment, $args, $depth) {
    $GLOBALS['comment'] = $comment;
    ?>
    <?php if ($comment->comment_approved == '1'): ?>
        <li>
            <article id="comment-<?php comment_ID() ?>">
                <?php echo get_avatar($comment); ?>
                <h4><?php comment_author_link() ?></h4>
                <time><a href="#comment-<?php comment_ID() ?>" pubdate><?php comment_date() ?> at <?php comment_time() ?></a></time>
                <?php comment_text() ?>
            </article>
            <?php
        endif;
    }

    //===========++++++includes++++++++=========================================
    include 'shortcodes.php';
    //widgets-----------
    include 'widgets/text_widget.php';
    include 'widgets/promo_box_widget.php';
    include 'widgets/latest_project_widget.php';
    include 'widgets/gallery_widget.php';
    include 'widgets/main_slider_widget.php';
    include 'widgets/our_clients_widget.php';
    include 'widgets/recent_work_widget.php';
    include 'widgets/services_widget.php';
    include 'widgets/testimonials_widget.php';
    include 'widgets/map_address_widget.php';
    include 'widgets/posts_comments_widget.php';
    include 'widgets/recent_comments_widget.php';
    include 'widgets/categories_widget.php';
    include 'widgets/flickr_widget.php';
    include 'widgets/twitter_widget.php';

    //===========++++++End Includes++++=========================================
    //content width
    if (!isset($content_width))
        $content_width = 960;

    //get template name
    add_filter('template_include', 'var_template_include', 1000);

    function var_template_include($t) {
        $GLOBALS['current_theme_template'] = basename($t);
        return $t;
    }

    function get_current_template($echo = false) {
        if (!isset($GLOBALS['current_theme_template']))
            return false;
        if ($echo)
            echo $GLOBALS['current_theme_template'];
        else
            return $GLOBALS['current_theme_template'];
    }

    //Blog page
    function strip_images($content) {
        return preg_replace('/<img[^>]+./', '', $content);
    }

    function cut_content($content, $nr_chars = '200') {
        $str = wordwrap($content, $nr_chars);
        $str = explode("\n", $str);
        $str = $str[0] . '...';
        return $str;
    }

    function cut_shortcodes($content) {
        return preg_replace('@\[.*?\]@', '', $content);
    }

    function no_slider($content) {
        return preg_replace("@(<div class=\'slider\'.*?</div>\s*</div>\s*</div>)@is", ' ', $content);
    }

    function echo_first_image($postID) {
        $args = array(
            'numberposts' => 1,
            'order' => 'ASC',
            'post_mime_type' => 'image',
            'post_parent' => $postID,
            'post_status' => null,
            'post_type' => 'attachment'
        );

        $attachments = get_children($args);

        //print_r($attachments);

        if ($attachments) {
            foreach ($attachments as $attachment) {
                $image_attributes = wp_get_attachment_image_src($attachment->ID, 'thumbnail') ? wp_get_attachment_image_src($attachment->ID, 'thumbnail') : wp_get_attachment_image_src($attachment->ID, 'full');

                echo '<img src="' . wp_get_attachment_thumb_url($attachment->ID) . '" class="current">';
            }
        }
    }

    //------comment form-----------------------------
    function comment_field($field) {
        return preg_replace("@\n@is", " ", $field);
    }

    //===============================Sidebars===================================

    if (function_exists('register_sidebar')) {
        //========Blog sidebar==============
        register_sidebar(array(
            'name' => 'Blog Sidebar',
            'id' => 'blogsidebar',
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========Main Slider===============
        register_sidebar(array(
            'name' => 'Home Mainslider',
            'id' => 'mainslider',
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========Main Content====================
        register_sidebar(array(
            'name' => 'Home Main Content',
            'id' => 'maincontent',
            'description' => __('The main content area'),
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========About Content====================
        register_sidebar(array(
            'name' => 'About Page Content',
            'id' => 'aboutcontent',
            'description' => __('The about content area'),
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========Portfolio Content====================
        register_sidebar(array(
            'name' => 'Portfolio Page Content',
            'id' => 'portfoliocontent',
            'description' => __('The portfolio content area'),
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========Portfolio Content====================
        register_sidebar(array(
            'name' => 'Contact Page Content',
            'id' => 'contactcontent',
            'description' => __('The contact content area'),
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========Single project Top====================
        register_sidebar(array(
            'name' => 'Single Project Top',
            'id' => 'singleproject_top',
            'description' => __('The top area of single project , for info and slider'),
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========Single project Bottom====================
        register_sidebar(array(
            'name' => 'Single Project Bottom',
            'id' => 'singleproject_bottom',
            'description' => __('The bottom area of single project '),
            'before_widget' => '',
            'after_widget' => '',
        ));
        //========404=====================================
        register_sidebar(array(
            'name' => 'Error 404 Page',
            'id' => '404error',
            'description' => __('The bottom content for widgets '),
            'before_widget' => '',
            'after_widget' => '',
            'before_title' => '',
            'after_title' => ''
        ));
    }

    //====================View count for single posts===========================
    function wpb_set_post_views($postID) {
        $count_key = 'wpb_post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if ($count == '') {
            $count = 0;
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
        } else {
            $count++;
            update_post_meta($postID, $count_key, $count);
        }
    }

//To keep the count accurate, lets get rid of prefetching
    remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

    function wpb_get_post_views($postID) {
        $count_key = 'wpb_post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if ($count == '') {
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
            return "0 View";
        }
        return $count . ' Views';
    }

    //===================================Menus==================================
    function register_my_menus() {
        register_nav_menus(
                array('header_menu' => __('Header menu'))
        );
    }

    add_action('init', 'register_my_menus');

    //====================================Slider================================
//    include 'slider.php';
    //extras
    add_theme_support('post-thumbnails');

//==============================++++++Admin Panel++++++++=======================
    //-------Menu and pages--------------------------------
    add_action("admin_menu", "setup_theme_admin_menus");

    function setup_theme_admin_menus() {
        //-------adding css nad javascript to admin head--------
        if (isset($_GET['page']) && $_GET['page'] == 'custom_theme_settings') {
            add_action('admin_head', 'theme_options_page_head');
        }
        $icon_url = get_template_directory_uri() . '/images/favicon_belle.ico';
        add_menu_page('Theme settings', 'Belle', 'manage_options', 'custom_theme_settings', 'theme_options_do_page', get_template_directory_uri() . '/images/favicon_belle.ico');

    }

    //-------theme settings--------------------------------
    function theme_options_init() {
        register_setting('the_theme_options', 'theme_options');
    }

    add_action('admin_init', 'theme_options_init');

    function theme_options_page_head() {
        wp_enqueue_script('admin', get_template_directory_uri() . '/js/bootstrap.js', array('jquery'), '2.2', FALSE);
		wp_register_style('admin_css', get_template_directory_uri() . '/css/style_admin.css');
		wp_register_style('admin_bootstrap_css', get_template_directory_uri() . '/css/bootstrap.css');
		wp_enqueue_style('admin_bootstrap_css');
		wp_enqueue_style('admin_css');
        ?>
        <script type="text/javascript">
            function ClipBoard()
            {
                Copied = jQuery("#exportcode");
                Copied.document.execCommand("Copy");
            }
            jQuery(document).ready(function($) {
                if (jQuery(".logo_field:eq(2)").attr('value') != '') {
                    jQuery(".logo_field:eq(0),.logo_field:eq(1)").css('background-color','#f1f1f1')
                }else if(jQuery(".logo_field:eq(1)").attr('value') != ''){
                    jQuery(".logo_field:eq(0)").css('background-color','#f1f1f1')
                    jQuery(".logo_field:eq(1)").css('background-color','#fff')
                }else {
                    jQuery(".logo_field").css('background-color','#fff')
                }
                jQuery(".logo_field").on('focusout focusin keyup', function() {
                    if (jQuery(".logo_field:eq(2)").attr('value') != '') {
                        jQuery(".logo_field:eq(0),.logo_field:eq(1)").css('background-color','#f1f1f1')
                    }else if(jQuery(".logo_field:eq(1)").attr('value') != ''){
                        jQuery(".logo_field:eq(0)").css('background-color','#f1f1f1')
                        jQuery(".logo_field:eq(1)").css('background-color','#fff')
                    }else {
                        jQuery(".logo_field").css('background-color','#fff')
                    }
                })


                jQuery('#add_skill').unbind('click').live('click', function(){
                    var skills = jQuery('.skills_nr').attr("value");
                    if (isNaN(skills))
                        skills = 0 ;
                    skills++;
                    jQuery('.skills_nr').attr("value", skills)
                    jQuery('#skills').before('<div class="row"><div class="span2" class="skill_order"><i>Skill '+skills+' unsaved</i></div><div class="span5"><input id="theme_options[skill_'+skills+']" class="skill" type="text" name="theme_options[skill_'+skills+']" /><label for="theme_options[skill_'+skills+']"> Enter the skill name</label></div><div class="span3"><input id="theme_options[skill_'+skills+'_val]" type="text" class="skill_val" name="theme_options[skill_'+skills+'_val"] /><label for="theme_options[skill_'+skills+'_val]">Enter the skill Value from 1 to 100</label></div><div class="span2"><input type="button" class="btn btn-danger remove_skill" value="Remove Skill" /></div></div>')
                })
                jQuery('.remove_skill').unbind('click').live('click', function(){
                    var skills = jQuery('.skills_nr').attr("value");
                    if (isNaN(skills) || skills == 0)
                        skills = 1 ;
                    skills--;
                    jQuery('.skills_nr').attr("value", skills)
                    jQuery(this).parent().parent().remove();
                    // start updating attributes after removing a skill
                    var i;
                    i = 1;
                    jQuery('.skill').each(function(){
                        jQuery(this).attr({
                            'id':'theme_options[skill_'+i+']',
                            'name':'theme_options[skill_'+i+']'
                        })
                        i++;
                    })
                    var i = 1;
                    jQuery('.skill_order').each(function(){
                        jQuery(this).html("Skill " + i)
                        i++;
                    })
                    var i = 1;
                    jQuery('.skill_val').each(function(){
                        jQuery(this).attr({
                            'id':'theme_options[skill_'+i+'_val]',
                            'name':'theme_options[skill_'+i+'_val]'
                        })
                        i++;
                    })
                    //end updating attributes after removing a skill
                })
            });
        </script>
        <?php
    }

    function theme_options_do_page() {
        global $select_options;
        if (!isset($_REQUEST['settings-updated']))
            $_REQUEST['settings-updated'] = false;
        $options = get_option('theme_options');
        if (isset($_POST["import_code"])) {
            $import_code = $_POST['import_code'];
            $import_code = base64_decode($import_code);
            $options = unserialize($import_code);
        }
        
        //includin admin markup=================================================
		require 'admin_panel.php';
    }

    //=======Customizer=========
    function theme_customize_register($wp_customize) {

        //Settings--------------------
        $wp_customize->add_setting('site_color', array(
            'default' => '#089FC4',
            'transport' => 'refresh',
        ));
        $wp_customize->add_setting('layout', array(
            'default' => '',
            'transport' => 'refresh',
        ));
        $wp_customize->add_setting('background_color', array(
            'default' => '#fff',
            'transport' => 'refresh',
        ));
        $wp_customize->add_setting('background_texture', array(
            'default' => '',
            'transport' => 'refresh',
        ));
        $wp_customize->add_setting('font', array(
            'default' => '',
            'transport' => 'refresh',
        ));

        //Sections-------------------
        $wp_customize->add_section('site_color', array(
            'title' => __('Color', 'theme'),
            'priority' => 40,
        ));
        $wp_customize->add_section('background_texture', array(
            'title' => __('Layout & Textures', 'theme'),
            'priority' => 30,
        ));
        $wp_customize->add_section('font', array(
            'title' => __('Text Font', 'theme'),
            'priority' => 50,
        ));

        //Controls-------------------
        $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'site_color', array(
                    'label' => __('Site Color', 'theme'),
                    'section' => 'site_color',
                    'settings' => 'site_color',
                )));
        $wp_customize->add_control('layout', array(
            'label' => __('Site Layout', 'theme'),
            'type' => 'select',
            'section' => 'background_texture',
            'settings' => 'layout',
            'choices' => array(
                '' => 'Full Width',
                'boxed' => 'Boxed Layout'
            )
        ));
        $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'background_color', array(
                    'label' => __('Background Color', 'theme'),
                    'section' => 'site_color',
                    'settings' => 'background_color',
                )));
        $wp_customize->add_control('background_texture', array(
            'label' => __('Background Texture', 'theme'),
            'section' => 'background_texture',
            'settings' => 'background_texture',
            'type' => 'radio',
            'choices' => array(
                '' => 'No Texture',
                'bodytexture01' => 'Texture 1',
                'bodytexture02' => 'Texture 2',
                'bodytexture03' => 'Texture 3',
                'bodytexture04' => 'Texture 4',
                'bodytexture05' => 'Texture 5',
                'bodytexture06' => 'Texture 6',
                'bodytexture07' => 'Texture 7',
                'bodytexture08' => 'Texture 8',
                'bodytexture09' => 'Texture 9',
                'bodytexture10' => 'Texture 10',
            ),
        ));
        $wp_customize->add_control('font', array(
            'label' => __('Text Font', 'theme'),
            'section' => 'font',
            'settings' => 'font',
            'type' => 'radio',
            'choices' => array(
                "'Open Sans', sans-serif" => "Open Sans",
                "Lato, sans-serif" => 'Lato',
                "'PT Sans Narrow, sans-serif'" => 'PT Sans Narrow',
                "Varela, sans-serif" => 'Varela',
                "'Droid-sans', sans-serif" => 'Droid sans',
                "'PT Sans Caption'" => 'PT Sans Caption',
                "Magra, sans-serif" => 'Magra',
                "Chivo, sans-serif" => 'Chivo',
                "Verdana, sans-serif" => 'Veranda',
                "Tahoma, sans-serif" => 'Tahoma',
                "Arial, sans-serif" => 'Arial',
            ),
        ));
    }

    add_action('customize_register', 'theme_customize_register');

    function theme_customize_css() {
        ?>
        <script type="text/javascript">
            (function($) {
                $(document).ready( function() {
                    $('#commentform').wrapInner('<div class="contact_form">');
                });
            })(jQuery);
        </script>
        <?php
    }

    add_action('wp_head', 'theme_customize_css');

//===========================+++++Breadcrumbs+++++++========================
    function dimox_breadcrumbs() {

        $showOnHome = 1; // 1 - show breadcrumbs on the homepage, 0 - don't show
        $delimiter = '/'; // delimiter between crumbs
        $home = 'Home'; // text for the 'Home' link
        $showCurrent = 1; // 1 - show current post/page title in breadcrumbs, 0 - don't show
        $before = '<a class="active">'; // tag before the current crumb
        $after = '</a>'; // tag after the current crumb

        global $post;
        $homeLink = get_bloginfo('url');

        if (is_home() || is_front_page()) {

            if ($showOnHome == 1)
                echo '<a href="' . $homeLink . '">' . $home . '</a></div>';
        } else {

            echo '<a href="' . $homeLink . '">' . $home . '</a> ' . $delimiter . ' ';

            if (is_category()) {
                $thisCat = get_category(get_query_var('cat'), false);
                if ($thisCat->parent != 0)
                    echo get_category_parents($thisCat->parent, TRUE, ' ' . $delimiter . ' ');
                echo $before . 'Archive by category "' . single_cat_title('', false) . '"' . $after;
            } elseif (is_search()) {
                echo $before . 'Search results for "' . get_search_query() . '"' . $after;
            } elseif (is_day()) {
                echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
                echo '<a href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
                echo $before . get_the_time('d') . $after;
            } elseif (is_month()) {
                echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
                echo $before . get_the_time('F') . $after;
            } elseif (is_year()) {
                echo $before . get_the_time('Y') . $after;
            } elseif (is_single() && !is_attachment()) {
                if (get_post_type() != 'post') {
                    $post_type = get_post_type_object(get_post_type());
                    $slug = $post_type->rewrite;
                    echo '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a>';
                    if ($showCurrent == 1)
                        echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
                } else {
                    $cat = get_the_category();
                    $cat = $cat[0];
                    $cats = get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
                    if ($showCurrent == 0)
                        $cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats);
                    echo $cats;
                    if ($showCurrent == 1)
                        echo $before . get_the_title() . $after;
                }
            } elseif (!is_single() && !is_page() && get_post_type() != 'post' && !is_404()) {
                $post_type = get_post_type_object(get_post_type());
                echo $before . $post_type->labels->singular_name . $after;
            } elseif (is_attachment()) {
                $parent = get_post($post->post_parent);
                $cat = get_the_category($parent->ID);
                $cat = $cat[0];
                echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
                echo '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a>';
                if ($showCurrent == 1)
                    echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
            } elseif (is_page() && !$post->post_parent) {
                if ($showCurrent == 1)
                    echo $before . get_the_title() . $after;
            } elseif (is_page() && $post->post_parent) {
                $parent_id = $post->post_parent;
                $breadcrumbs = array();
                while ($parent_id) {
                    $page = get_page($parent_id);
                    $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
                    $parent_id = $page->post_parent;
                }
                $breadcrumbs = array_reverse($breadcrumbs);
                for ($i = 0; $i < count($breadcrumbs); $i++) {
                    echo $breadcrumbs[$i];
                    if ($i != count($breadcrumbs) - 1)
                        echo ' ' . $delimiter . ' ';
                }
                if ($showCurrent == 1)
                    echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
            } elseif (is_tag()) {
                echo $before . 'Posts tagged "' . single_tag_title('', false) . '"' . $after;
            } elseif (is_author()) {
                global $author;
                $userdata = get_userdata($author);
                echo $before . 'Articles posted by ' . $userdata->display_name . $after;
            } elseif (is_404()) {
                echo $before . 'Error 404' . $after;
            }

            if (get_query_var('paged')) {
                if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author())
                    echo ' (';
                echo __('Page') . ' ' . get_query_var('paged');
                if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author())
                    echo ')';
            }
        }
    }

// end dimox_breadcrumbs()
require_once('php/twitteroauth/twitteroauth.php');
require_once('php/twitter.php');

//===================================TeslaSecurity Check==================================
function tt_get_username(){
    if(file_exists(get_template_directory() . '/theme_config/tt_license.txt'))
        if($username = file_get_contents(get_template_directory() . '/theme_config/tt_license.txt'))
            return base64_decode($username);
    return NULL;
}

function tt_check_username(){
    $state='';
    $username = tt_get_username();
    if ($username){
        $result = get_transient( 'security_api_result' );
        if(!$result){
                if(ini_get('allow_url_fopen')){
                    $api = file_get_contents( 'http://teslathemes.com/amember/api/check-access/by-login?_key=n7RYtMjOm9qjzmiWQlta&login=' . $username);
                }
                if(empty($api) && function_exists('curl_init')){
                    $api = curl_get_file_contents('http://teslathemes.com/amember/api/check-access/by-login?_key=n7RYtMjOm9qjzmiWQlta&login=' . $username);
                }
                if(!empty($api)){
                    $result = json_decode($api);
                    set_transient( 'security_api_result', $result, 30 * MINUTE_IN_SECONDS );
                }else{
                    $this->state = 'no data' ;
                }
        }

        if ( !(empty($result->ok)) ){  //if username exists
            if (!empty($result->subscriptions)){    //if any active subscriptions or blocked product active
                if ( !empty($result->subscriptions->{28}) ){    //if any blocking product active
                    $state = 'blocked' ;
                }elseif(!empty($result->subscriptions->{34})){  //if any warning product active
                    $state = 'warning' ;
                }
            }
        }elseif( !in_array( $username, array( 'tt_general_user','tt_other_marketplaces_user' ) ) )
            $state = 'corrupt';

    }else
        $state = 'corrupt';
    return $state;
}

function curl_get_file_contents($URL){
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_URL, $URL);
    $contents = curl_exec($c);
    curl_close($c);

    if ($contents) 
        return $contents;
    else 
        return FALSE;
}

function tt_security_check(){ // call this function somewhere in the page code to block it if account disabled on TT
    $state = tt_check_username();
    return tt_throw_errors($state);
}

function tt_throw_errors($state){
    switch ($state) {
        case 'active':
            break;
        case 'warning' :
            tt_error_message($state,true);
            break;
        case 'no data':
            tt_error_message($state,true);
            break;
        case 'blocked':
            tt_error_message($state);
            return FALSE;
        case 'corrupt':
            tt_error_message($state, NULL, "<span>Note :</span> Don't change the code or license file contents please.");
            return FALSE;
    }
    return TRUE;
}

function tt_error_message($state,$just_warning=NULL,$custom=NULL){
    echo "<div id='result_content'><div id='tt_import_alert'>";
    if ( $custom )
        echo $custom;
    if ( $just_warning )
        echo '<span>WARNING :</span> We noticed some fraudulous activity with our theme or couldn\'t connect to our servers for some reasons. Please contact us in 5 days to fix this or framework page will be blocked.<br> <span>State : ' . $state . '</span>';
    else
        echo 'The options page is <span>blocked</span> by TeslaThemes due to some <span>fraudulous action</span>.<br> Please contact us at hi@teslathemes.com or click the link below to correct your license if you think that this is a mistake. <br><span>State : ' . $state . '</span>';
    echo "</div><a href='http://teslathemes.com/contact/' class='btn'>Contact TeslaThemes</a></div>";
    return;
}

    //Login Page
    function custom_login() {
        echo '<link rel="stylesheet" type="text/css" href="' . get_bloginfo('template_directory') . '/css/login.css" />'."\n";
        echo '<script type="text/javascript" src="'.get_bloginfo('template_directory').'/js/jquery.min.js"></script>'."\n";
    }
    add_action('login_head', 'custom_login');

    //Login Page Title
    function custom_headertitle ( $title ) {
        return get_bloginfo('name');
    }
    add_filter('login_headertitle','custom_headertitle');

    //Login Page Link
    function custom_loginlogo_url($url) {
        return esc_url( home_url('/') );
    }
    add_filter( 'login_headerurl', 'custom_loginlogo_url' );

    //Login Page Footer
    function custom_html() {
        echo '<div class="footer">'."\n";
        echo '<p>Copyright &copy; '.date('Y').' All Rights Reserved</p>'."\n";
        echo '</div>'."\n";
        echo '<script type="text/javascript" src="'.get_bloginfo('template_directory').'/js/resizeBg.js"></script>'."\n";
        echo '<script type="text/javascript">'."\n";
        echo 'jQuery("body").prepend("<div class=\"loading\"><img src=\"'.get_bloginfo('template_directory').'/images/login_loading.gif\" width=\"58\" height=\"10\"></div><div id=\"bg\"><img /></div>");'."\n";
        echo 'jQuery(\'#bg\').children(\'img\').attr(\'src\', \''.get_bloginfo('template_directory').'/images/login_bg.jpg\').load(function(){'."\n";
        echo '  resizeImage(\'bg\');'."\n";
        echo '  jQuery(window).bind("resize", function() { resizeImage(\'bg\'); });'."\n";
        echo '  jQuery(\'.loading\').fadeOut();'."\n";
        echo '});';
        echo '</script>'."\n";
    }
    add_action('login_footer', 'custom_html');

    /*精简后台代码*/
    function disable_dashboard_widgets() {   
        remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');//近期评论 
        remove_meta_box('dashboard_recent_drafts', 'dashboard', 'normal');//近期草稿
        remove_meta_box('dashboard_primary', 'dashboard', 'core');//wordpress博客  
        remove_meta_box('dashboard_secondary', 'dashboard', 'core');//wordpress其它新闻  
        remove_meta_box('dashboard_right_now', 'dashboard', 'core');//wordpress概况  
        remove_meta_box('dashboard_incoming_links', 'dashboard', 'core');//wordresss链入链接  
        remove_meta_box('dashboard_plugins', 'dashboard', 'core');//wordpress链入插件  
        remove_meta_box('dashboard_quick_press', 'dashboard', 'core');//wordpress快速发布   
    }  
    add_action('admin_menu', 'disable_dashboard_widgets');

    // 隐藏所有更新提示(比如插件、主题等更新)
    add_action('admin_menu','hide_admin_notices');
        function hide_admin_notices() {
            remove_action( 'admin_notices', 'update_nag', 3 );
    }

    // 移除仪表盘左侧“更新”这个子栏目
    add_action('admin_menu', 'remove_menus', 102);
        function remove_menus() {
            global $submenu;
            remove_submenu_page ( 'index.php', 'update-core.php' );
    }

    //  屏蔽后台页脚版本号
    function change_footer_admin () {return '';}
    add_filter('admin_footer_text', 'change_footer_admin', 9999);
    function change_footer_version() {return '';}
    add_filter( 'update_footer', 'change_footer_version', 9999);

    //屏蔽 WP 后台“显示选项”和“帮助”选项卡
    function remove_screen_options(){ return false;}
        add_filter('screen_options_show_screen', 'remove_screen_options');
     
        add_filter( 'contextual_help', 'wpse50723_remove_help', 999, 3 );
     
        function wpse50723_remove_help($old_help, $screen_id, $screen){
        $screen->remove_help_tabs();
        return $old_help;
    }


    //屏蔽后台导航栏LOGO、更新、评论

    function annointed_admin_bar_remove() {
            global $wp_admin_bar;
            /* Remove their stuff */
            $wp_admin_bar->remove_menu('wp-logo');
            $wp_admin_bar->remove_menu('updates'); //插件更新信息
            $wp_admin_bar->remove_menu('comments');  //评论
    }
    add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove', 0);

    


